package cn.sinata.wanglin.neighbor.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.PermissionManager;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.ContactsFriendsAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Contact;
import cn.sinata.wanglin.model.PhoneContact;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultSubscriber;
import cn.sinata.wanglin.utils.ContactUtils;
import cn.sinata.wanglin.view.BladeView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

public class ContactsFriendsActivity extends TitleActivity implements SwipeRefreshRecyclerLayout.OnRefreshListener{

    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;
    @BindView(R.id.mLetterListView)
    BladeView mLetterListView;
    private ContactsFriendsAdapter contactsFriendsAdapter;
    private ArrayList<Contact> mContacts = new ArrayList<>();
    private ArrayList<PhoneContact> mPhoneContacts = new ArrayList<>();
    private HashMap<String,Integer> letters = new HashMap<>();
    private String userId;

    @Override
    protected int setContentId() {
        return R.layout.activity_contacts_friends;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("通讯录朋友");

        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);

        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(this));
        mSwipeRefreshLayout.setMode(SwipeRefreshRecyclerLayout.Mode.Top);
        mSwipeRefreshLayout.setAdapter(setAdapter());
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(ContextCompat.getColor(this,R.color.dividing_line_color))
                .size(1)
                .build());

        mLetterListView.setOnItemClickListener(new BladeView.OnItemClickListener() {
            @Override
            public void onItemClick(String s) {
                selectRecyclerView(s);
            }
        });

        boolean hasPermission = PermissionManager.request(this, Manifest.permission.WRITE_CONTACTS,"读取您的通讯录",10);
        if (hasPermission) {
            showDialog();
            getContacts();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length <= 0) {
            return;
        }
        SharedPreferencesUtils.save(permissions[0],false);
        if (requestCode == 10 && permissions[0].equals(Manifest.permission.READ_CONTACTS)) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showDialog();
                getContacts();
            }
        }
    }

    private void getContacts(){
        Observable.create(new Observable.OnSubscribe<ArrayList<PhoneContact>>() {
            @Override
            public void call(Subscriber<? super ArrayList<PhoneContact>> subscriber) {
                mPhoneContacts = ContactUtils.getPhoneContacts(mContext,true);
//                if (mPhoneContacts == null || mPhoneContacts.size() == 0) {
//
//                } else {
                subscriber.onNext(mPhoneContacts);
                subscriber.onCompleted();
//                }
            }
        }).subscribeOn(Schedulers.io())
        .flatMap(new Func1<List<PhoneContact>, Observable<ResultData<ArrayList<Contact>>>>() {
            @Override
            public Observable<ResultData<ArrayList<Contact>>> call(List<PhoneContact> phoneContacts) {
                ArrayList<String> strings = new ArrayList<>();
                for (PhoneContact phoneContact : phoneContacts) {
                    strings.add(phoneContact.getContactId());
                }
                JSONArray array = new JSONArray(strings);
                return HttpManager.getNewFriendsByContacts(userId, array.toString());
            }
        })
        .flatMap(new Func1<ResultData<ArrayList<Contact>>, Observable<Contact>>() {
            @Override
            public Observable<Contact> call(ResultData<ArrayList<Contact>> arrayListResultData) {
                if (arrayListResultData.getCode().equals("SUCCESS")) {
                    ArrayList<Contact> contacts = arrayListResultData.getData();
                    for (Contact contact : contacts) {
                        //循环查询当前注册用户在手机的备注名。
                        for (PhoneContact mPhoneContact : mPhoneContacts) {
                            if (mPhoneContact.getContactId().equals(contact.getPhone())) {
                                contact.setContactName(mPhoneContact.getName());
                                break;
                            }
                        }
                    }
                    return Observable.from(contacts);
                }
                return Observable.error(new Throwable(arrayListResultData.getMessage()));
            }
        })
        .toSortedList(new Func2<Contact, Contact, Integer>() {
            @Override
            public Integer call(Contact phoneContact, Contact phoneContact2) {
                if(phoneContact.getFirstChar().equals(phoneContact2.getFirstChar())){
                    return phoneContact.getName().compareTo(phoneContact2.getName());
                }else{
                    if("#".equals(phoneContact.getFirstChar())){
                        return -1;
                    }else if("#".equals(phoneContact2.getFirstChar())){
                        return 1;
                    }
                    return phoneContact.getFirstChar().compareTo(phoneContact2.getFirstChar());
                }
            }
        })
        .doOnNext(new Action1<List<Contact>>() {
            @Override
            public void call(List<Contact> phoneContacts) {
                mContacts.clear();
                for (int i = 0; i < phoneContacts.size(); i++) {
                    Contact contact = phoneContacts.get(i);

                    if(!letters.containsKey(contact.getFirstChar())){
                        letters.put(contact.getFirstChar(),i);
                    }

                }
                mContacts.addAll(phoneContacts);
            }
        })
        .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultSubscriber<List<Contact>>(this){
                    @Override
                    public void onNext(List<Contact> phoneContacts) {
                        super.onNext(phoneContacts);
                        dismissDialog();
                        mSwipeRefreshLayout.setRefreshing(false);
                        contactsFriendsAdapter.setLetters(letters);
                        contactsFriendsAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissDialog();
                        showToast(e.getMessage());
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    protected RecyclerView.Adapter setAdapter() {

        contactsFriendsAdapter = new ContactsFriendsAdapter(mContacts);
        View headerView = View.inflate(this, R.layout.header_contact_friend_layout,null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        contactsFriendsAdapter.setHeaderView(headerView);
        return contactsFriendsAdapter;
    }

    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        getContacts();
    }

    @Override
    public void onLoadMore() {

    }

    private void selectRecyclerView(String s) {
        if (s.equals("↑") || s.equals("#")) {
            mSwipeRefreshLayout.getRecyclerView().scrollToPosition(0);
        } else {
            if(letters.containsKey(s)){
                mSwipeRefreshLayout.getRecyclerView().scrollToPosition(letters.get(s));
            }
        }
    }
}
